package com.wing.res.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.device.model.entity.DeviceModel;
import com.wing.device.service.DeviceModelService;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductType;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductTypeService;
import com.wing.res.model.entity.*;
import com.wing.res.model.request.ResProProcessAddForm;
import com.wing.res.model.response.DeviceOrWorkVo;
import com.wing.res.model.response.ProductCountInWarhouseVo;
import com.wing.res.model.response.ResProTaskSearchVo;
import com.wing.res.service.*;
import com.wing.sell.model.entity.OrderProEnclosure;
import com.wing.sell.service.OrderProEnclosureService;
import com.wing.storage.service.ProductInventoryService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品工艺路线
 *
 * @version 1.1.0
 * @Author hz
 * @Date 2024-09-24 17:08
 **/
@Slf4j
@Validated
@Api(value = "产品规划-工艺规划任务", tags = "#/res/planning/processPlan/processTask")
@RestController("resProEchnologyParamController")
@RequestMapping("echnologyParam/admin/echnologyParam")
public class ResProEchnologyParamController {

    @Autowired
    private ResProTaskService resProTaskService;

    @Autowired
    private OrderProEnclosureService orderProEnclosureService;

    @Autowired
    private ResBenchmarkBookEchnologyService resBenchmarkBookEchnologyService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private DeviceModelService deviceModelService;

    @Autowired
    private ResBenchmarkBookEchnologySkuService resBenchmarkBookEchnologySkuService;

    @Autowired
    private ProductInventoryService productInventoryService;

    @Autowired
    private ResBenchmarkBookEchnologyQualityService resBenchmarkBookEchnologyQualityService;

    @ApiOperation(value = "查研发任务列表", notes = "搜索-任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ResProTaskSearchVo> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long productTypeId
            ,Long customerId
            ,String customerProCode
            ,String productStatus
            ,String customerProFigure
            ,String givenStartTimed
    ) {
        Page<ResProTaskSearchVo> pg = new Page<>(page, limit);
        Map<String,Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("customerProCode", customerProCode);
        map.put("productStatus", productStatus);
        if (StrUtil.isNotEmpty(givenStartTimed)){
            // 使用 split 方法分割字符串
            String[] dates = givenStartTimed.split(" 至 ");
            // 获取开始和结束日期
            String startDate = dates[0];
            String endDate = dates[1];
            map.put("givenStartTime", startDate);
            map.put("givenEndTime", endDate);
        }
        map.put("customerProFigure", customerProFigure);
        map.put("status", MaintenanceEnum.Task_Status_Enum.DQR.getCode());
        map.put("productTypeId", productTypeId);
        String noStatus = "";
        Page<ResProTaskSearchVo> list = resProTaskService.pageList4app(pg, map, noStatus);
        list.getRecords().forEach(info-> {
            info.setProductStatus(MaintenanceEnum.Task_Status_Enum.getNameByCode(info.getProductStatus()));
            info.setSource(MaintenanceEnum.Task_Source_Enum.getNameByCode(info.getSource()));
            QueryWrapper<OrderProEnclosure> enclosureQueryWrapper = new QueryWrapper<>();
            enclosureQueryWrapper.eq("task_id",info.getId());
            OrderProEnclosure one = orderProEnclosureService.getOne(enclosureQueryWrapper);
            if (ObjectUtil.isNotEmpty(one)){
                info.setFileUrl(one.getFileUrl());
                info.setCusProductFigure(one.getFileName());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 确认
     * @param id
     * @return
     */
    @ApiOperation(value = "点击确认", notes = "确认")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/confirm/{id}")
    public JsonResult confirm(@PathVariable("id") String id) {
        if (orderProEnclosureService.confirm(id) > 0) {
            return JsonResult.success("操作成功");
        }
        return JsonResult.fail("操作失败");
    }


    /**
     * 添加产品工序
     * @param resProProcessAddForm
     * @return
     */
    @ApiOperation(value = "添加产品工序", notes = "添加产品工序")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addSkuProcess")
    public JsonResult addSkuProcess(@RequestBody ResProProcessAddForm resProProcessAddForm) {
        if (resProTaskService.addSkuProcess(resProProcessAddForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    /**
     * 初始化任务详情
     * @param bookId 查询基准书工序信息
     * @return
     */
    @ApiOperation(value = "查看研发任务详情", notes = "查看工序-基准书id")
    @GetMapping("/getEchonlogyInfoBy/{bookId}")
    public JsonResult getEchonlogyInfoBy(@PathVariable("bookId") String bookId) {

        Map<Long, ProductDetail> proMap = new HashMap<>();

        List<DeviceOrWorkVo> deviceModels = deviceModelService.devicelist();

        List<DeviceOrWorkVo> fessionlist = deviceModelService.fessionlist();

        List<ProductCountInWarhouseVo> productCountInWarhouse = productInventoryService.getProductCountInWarhouse();

        QueryWrapper<ResBenchmarkBookEchnology> echnologyQueryWrapper = new QueryWrapper<>();
        echnologyQueryWrapper.eq("book_id",bookId);
        echnologyQueryWrapper.eq("is_deleted",false);
        echnologyQueryWrapper.orderByAsc("sorted");
        List<ResBenchmarkBookEchnology> list = this.resBenchmarkBookEchnologyService.list(echnologyQueryWrapper);
        //查询出工序下的物料
        if (CollectionUtil.isNotEmpty(list)) {
            for (ResBenchmarkBookEchnology resBenchmarkBookEchnology : list) {

                resBenchmarkBookEchnology.setTypeName(MaintenanceEnum.gxTypeEmum.getNameByCode(resBenchmarkBookEchnology.getType()));
                resBenchmarkBookEchnology.setProcessType(resBenchmarkBookEchnology.getType());
                //设置类型
                QueryWrapper<ResBenchmarkBookEchnologySku> skuQueryWrapper = new QueryWrapper<>();
                skuQueryWrapper.eq("echnology_id",resBenchmarkBookEchnology.getId());
                skuQueryWrapper.eq("is_deleted",false);
                List<ResBenchmarkBookEchnologySku> skuList = resBenchmarkBookEchnologySkuService.list(skuQueryWrapper);
                if (CollectionUtil.isNotEmpty(skuList)) {
                    List<Long> collect = skuList.stream().map(ResBenchmarkBookEchnologySku::getProductDetailId).collect(Collectors.toList());
                    QueryWrapper<ProductDetail> queryWrapper = new QueryWrapper<>();
                    queryWrapper.in("id",collect);
                    List<ProductDetail> productDetails = this.productDetailService.list(queryWrapper);
                    if (CollectionUtil.isNotEmpty(productDetails)) {
                        proMap = productDetails.stream().collect(Collectors.toMap(ProductDetail::getId, info->info));
                    }

                    for (ResBenchmarkBookEchnologySku resBenchmarkBookEchnologySku : skuList) {
                        resBenchmarkBookEchnologySku.setSkuName(proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()) == null?"":proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()).getSkuName());
                        resBenchmarkBookEchnologySku.setSkuSpec(proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()) == null?"":proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()).getSkuSpec());
                        if (CollectionUtil.isNotEmpty(productCountInWarhouse)) {
                            for (ProductCountInWarhouseVo longBigDecimalMap : productCountInWarhouse) {
                                if (longBigDecimalMap.getProductDetailId().equals((resBenchmarkBookEchnologySku.getProductDetailId()))) {
                                    resBenchmarkBookEchnologySku.setHaveQuantity(longBigDecimalMap.getHaveQuantity());
                                }
                            }

                        }
                        resBenchmarkBookEchnologySku.setSkuCode(proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()) == null?"":proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()).getSkuCode());
                    }
                    resBenchmarkBookEchnology.setSkuList(skuList);
                }


                List<DeviceOrWorkVo> types = new ArrayList<>();
                if (StrUtil.isNotEmpty(resBenchmarkBookEchnology.getWorkstationNature()) &&MaintenanceEnum.workstationEmum.SBGW.getCode().equals(resBenchmarkBookEchnology.getWorkstationNature())){
                    resBenchmarkBookEchnology.setWorkstationNatureName(MaintenanceEnum.workstationEmum.getNameByCode(resBenchmarkBookEchnology.getWorkstationNature()));

                    for (DeviceOrWorkVo deviceModel : deviceModels) {
                        if (StrUtil.isNotEmpty(resBenchmarkBookEchnology.getDeviceType()) && resBenchmarkBookEchnology.getDeviceType().equals(deviceModel.getId().toString())) {
                            types.add(deviceModel);
                        }
                    }
                }else if(StrUtil.isNotEmpty(resBenchmarkBookEchnology.getWorkstationNature()) && MaintenanceEnum.workstationEmum.RGGW.getCode().equals(resBenchmarkBookEchnology.getWorkstationNature())){
                    resBenchmarkBookEchnology.setWorkstationNatureName(MaintenanceEnum.workstationEmum.getNameByCode(resBenchmarkBookEchnology.getWorkstationNature()));

                    for (DeviceOrWorkVo fession : fessionlist) {
                        if (StrUtil.isNotEmpty(resBenchmarkBookEchnology.getDeviceType()) && resBenchmarkBookEchnology.getDeviceType().equals(fession.getId().toString())) {
                            types.add(fession);
                        }
                    }
                }
                resBenchmarkBookEchnology.setDeviceTypeList(types);
            } //设备工位

        }
        return JsonResult.success(list);
    }

    /**
     * 查看工序详情
     * @param enchonlogyId 工序id
     * @return
     */
    @ApiOperation(value = "查询工序详情", notes = "查看工序-工序id")
    @GetMapping("/getEchonlogyBy/{enchonlogyId}")
    public JsonResult getEchonlogyInfoByEnchonlogyId(@PathVariable("enchonlogyId") String enchonlogyId) {
        ResBenchmarkBookEchnology resBenchmarkBookEchnology = this.resBenchmarkBookEchnologyService.getById(enchonlogyId);
        Map<Long, ProductDetail> proMap = new HashMap<>();
        //查询出工序下的物料
        if (ObjectUtil.isNotEmpty(resBenchmarkBookEchnology)) {
                QueryWrapper<ResBenchmarkBookEchnologySku> skuQueryWrapper = new QueryWrapper<>();
                skuQueryWrapper.eq("echnology_id",resBenchmarkBookEchnology.getId());
                skuQueryWrapper.eq("is_deleted",false);
                List<ResBenchmarkBookEchnologySku> skuList = resBenchmarkBookEchnologySkuService.list(skuQueryWrapper);
                if (CollectionUtil.isNotEmpty(skuList)) {
                    List<Long> collect = skuList.stream().map(ResBenchmarkBookEchnologySku::getProductDetailId).collect(Collectors.toList());
                    QueryWrapper<ProductDetail> queryWrapper = new QueryWrapper<>();
                    queryWrapper.in("id",collect);
                    List<ProductDetail> productDetails = this.productDetailService.list(queryWrapper);
                    if (CollectionUtil.isNotEmpty(productDetails)) {
                       proMap = productDetails.stream().collect(Collectors.toMap(ProductDetail::getId, info->info));
                    }
                    for (ResBenchmarkBookEchnologySku resBenchmarkBookEchnologySku : skuList) {
                        resBenchmarkBookEchnologySku.setSkuName(proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()) == null?"":proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()).getSkuName());
                        resBenchmarkBookEchnologySku.setSkuSpec(proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()) == null?"":proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()).getSkuSpec());
                        resBenchmarkBookEchnologySku.setSkuCode(proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()) == null?"":proMap.get(resBenchmarkBookEchnologySku.getProductDetailId()).getSkuCode());
                    }
                }
                resBenchmarkBookEchnology.setSkuList(skuList);

        }
        return JsonResult.success(resBenchmarkBookEchnology);
    }

    /**
     * 查看工序详情
     * @param bookId bookId
     * @return
     */
    @ApiOperation(value = "根据bookId查询工序", notes = "查看工序-bookId")
    @GetMapping("/getProcessInfoBy/{bookId}")
    public List<ResBenchmarkBookEchnology> getProcessInfoBy(@PathVariable("bookId") Long bookId) {
       QueryWrapper<ResBenchmarkBookEchnology> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("book_id",bookId);
       queryWrapper.eq("is_deleted",false);
       return resBenchmarkBookEchnologyService.list(queryWrapper);
    }

    /**
     * 查看工序详情
     * @param processId processId
     * @return
     */
    @ApiOperation(value = "根据processId查询工序", notes = "查看工序-processId")
    @GetMapping("/getProcessInfoByProcessId/{processId}")
    public ResBenchmarkBookEchnology getProcessInfoByProcessId(@PathVariable("processId") Long processId) {
        QueryWrapper<ResBenchmarkBookEchnology> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",processId);
        queryWrapper.eq("is_deleted",false);
        ResBenchmarkBookEchnology one = resBenchmarkBookEchnologyService.getOne(queryWrapper);
        if(ObjectUtil.isNotEmpty(one)){
            one.setWorkstationNatureName(MaintenanceEnum.workstationEmum.getNameByCode(one.getWorkstationNature()));
            one.setTypeName(MaintenanceEnum.gxTypeEmum.getNameByCode(one.getType()));
            one.setQualityNatureName(MaintenanceEnum.qualityNatureEmum.getNameByCode(one.getQualityNature()));
        }
        if (ObjectUtil.isNull(one)){
            return new ResBenchmarkBookEchnology();
        }
        return one;
    }


    /**
     * 查看工序详情
     * @param bookId bookId
     * @return
     */
    @ApiOperation(value = "根据工序查询检测项", notes = "查看工序-检测项目")
    @GetMapping("/getQualityInfoBy/{bookId}/{processId}")
    public List<ResBenchmarkBookEchnologyQuality> getQualityInfoBy(@PathVariable("bookId") Long bookId, @PathVariable("processId") Long processId) {
        QueryWrapper<ResBenchmarkBookEchnologyQuality> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id",bookId);
        queryWrapper.eq("process_id",processId);
        List<ResBenchmarkBookEchnologyQuality> list = resBenchmarkBookEchnologyQualityService.list(queryWrapper);
        return list;
    }


}
